package com.canlihao.ui.base;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.canlihao.ui.R;
import com.canlihao.ui.mvp.dialog.DialogLoading;
import com.canlihao.ui.mvp.view.BaseView;
import com.canlihao.ui.utils.AppManager;
import com.canlihao.ui.utils.IMEUtil;
import com.canlihao.ui.utils.NetChangeUtil;
import com.canlihao.ui.utils.ReLoadEvent;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.zyq.easypermission.EasyPermissionHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;

/*******
 *
 *Created by 李魏
 *
 *创建时间 2020/1/17
 *
 *类描述：
 *
 ********/
public abstract class BaseActivityNormal<P> extends AppCompatActivity{

    /**
     * presenter
     */
    public P presenter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());

        // 创建presenter
        presenter = onCreatePresenter();

        // 添加类集合队列
        AppManager.getAppManager().addActivity(this);
        // 注册ButterKnife
        ButterKnife.bind(this);
        // 注册EventBus
        EventBus.getDefault().register(this);
        //沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
//        QMUIStatusBarHelper.setStatusBarLightMode(this);
        QMUIStatusBarHelper.setStatusBarDarkMode(this);

        parseData();
        initView();
        initData();
        initListener();
        initReceiver();
    }

    /**
     * 广播-监听网络状态
     */
    BroadcastReceiver netReceiver =new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                @SuppressLint("MissingPermission") NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                if (null != networkInfo && networkInfo.isAvailable()) {
                    int type = networkInfo.getType();
                    String lastNetState = NetChangeUtil.getInstance().getLastNetState();

                    if(!TextUtils.isEmpty(lastNetState)
                            && !TextUtils.equals(lastNetState, String.valueOf(type))
                            && (TextUtils.equals(String.valueOf(type), "0") || TextUtils.equals(String.valueOf(type), "1"))){
                        // 登录状态，而且网络切换到有网状态，通知界面刷新
                        EventBus.getDefault().post(new ReLoadEvent());
                    }

                    switch (type) {
                        case ConnectivityManager.TYPE_MOBILE: // 移动网络
                            NetChangeUtil.getInstance().setLastNetState("0");
                            break;
                        case ConnectivityManager.TYPE_WIFI: // wifi网络
                            NetChangeUtil.getInstance().setLastNetState("1");
                            break;
                    }
                } else {
                    NetChangeUtil.getInstance().setLastNetState("-1");
                }
            }
        }
    };
    /**
     * 保证同一按钮在1秒内只会响应一次点击事件
     */
    public abstract class OnSingleClickListener implements View.OnClickListener {
        //两次点击按钮之间的间隔，目前为1000ms
        private static final int MIN_CLICK_DELAY_TIME = 1000;
        private long lastClickTime;

        public abstract void onSingleClick(View view);

        @Override
        public void onClick(View view) {
            long curClickTime = System.currentTimeMillis();
            if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                lastClickTime = curClickTime;
                onSingleClick(view);
            }
        }
    }
    /**
     * 同一按钮在短时间内可重复响应点击事件
     */
    public abstract class OnMultiClickListener implements View.OnClickListener {
        public abstract void onMultiClick(View view);

        @Override
        public void onClick(View v) {
            onMultiClick(v);
        }
    }
    /**
     * 布局文件(必须重写)
     */
    public abstract int getLayoutResId();

    /**
     * 创建presenter(需要的话重写)
     */
    public P onCreatePresenter() {
        return null;
    }

    /**
     * 解析数据
     */
    public void parseData(){}

    /**
     * 初始化视图
     */
    protected void initView() {}

    /**
     * 初始化数据
     */
    public void initData() {}

    /**
     * 初始化请求
     */
    public void initRequest() {}

    /**
     * 初始化时间监听
     */
    public void initListener() {}

    /**
     * 注册网络监听的广播
     */
    private void initReceiver() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction("android.net.ethernet.ETHERNET_STATE_CHANGED");
        timeFilter.addAction("android.net.ethernet.STATE_CHANGE");
        timeFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        timeFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        timeFilter.addAction("android.net.wifi.STATE_CHANGE");
        timeFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(netReceiver, timeFilter);
    }
    /**
     * 联网恢复-重新请求最新数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reLoad(ReLoadEvent event){
        initRequest();
    }


    @Override
    public void onBackPressed() {
        IMEUtil.closeIME(this);
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        IMEUtil.closeIME(this);
        super.onStop();
    }

    @Override protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        AppManager.getAppManager().finishActivity(this);
        if (null != netReceiver) {
            unregisterReceiver(netReceiver);
            netReceiver = null;
        }
        super.onDestroy();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //使用EasyPermissionHelper注入回调
        EasyPermissionHelper.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
